package com.daffodil.workable.factory.strategy;

import java.util.Map;

import org.springframework.http.HttpStatus;

import com.daffodil.util.HttpResponseEntity;
import com.daffodil.util.HttpUtils;
import com.daffodil.util.JacksonUtils;
import com.daffodil.util.StringUtils;
import com.daffodil.workable.entity.WorkableNode;
import com.daffodil.workable.entity.WorkableResult;
import com.daffodil.workable.factory.strategy.model.WorkableQiwei;
import com.daffodil.workable.entity.WorkableForm;
import com.daffodil.workable.util.WorkableUtils;

/**
 * -任务工作流-企微告警节点
 * @author yweijian
 * @date 2022年4月8日
 * @version 1.0
 * @description
 */
public class QiweiWorkableStrategy extends DefaultWorkableStrategy {
    
    private static final String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send";
    
    private static final String template = "{\"msgtype\": \"text\", \"text\": {\"content\": \"{}\",\"mentioned_mobile_list\": [{}]}}";
    
    @Override
    protected WorkableResult chain(WorkableNode workableNode, WorkableResult curtResult, WorkableResult lastResult) {
        
        WorkableForm workableForm = workableNode.getWorkableForm();
        if(StringUtils.isNull(workableForm)) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数为空", workableNode.getName());
        }

        WorkableQiwei workableQiwei = JacksonUtils.toJavaObject(workableForm.getNodeForm(), WorkableQiwei.class);
        if(StringUtils.isNull(workableQiwei)) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数为空或不规范", workableNode.getName());
        }
        
        if(StringUtils.isEmpty(workableQiwei.getKey())) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数【{}】为空", workableNode.getName(), "key");
        }
        
        if(StringUtils.isEmpty(workableQiwei.getMobile())) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数【{}】为空", workableNode.getName(), "mobile");
        }
        
        if(StringUtils.isEmpty(workableQiwei.getContent())) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数【{}】为空", workableNode.getName(), "content");
        }
        
        Map<String, Object> variables = lastResult.getVariables();
        String[] mobiles = workableQiwei.getMobile().split(WorkableQiwei.SPLIT_TAG);
        String content = WorkableUtils.getExpressionValue(workableQiwei.getContent(), variables);
        String params = StringUtils.format("key={}", workableQiwei.getKey());
        String body = StringUtils.format(template, content, StringUtils.join(mobiles, ","));
        HttpResponseEntity responseEntity = HttpUtils.sendSSLPost(url, params, body);
        
        curtResult.setStatus(responseEntity.getData().getStatus() == HttpStatus.OK.value());
        curtResult.setMessage(responseEntity.getData().getMessage());
        curtResult.setVariables(responseEntity.toHashMap());
        
        return curtResult;
    }

}
